package com.eatme.web.util;

import com.nimbusds.jose.JWSAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Random;

public class KeyGeneratorUtils {

    private KeyGeneratorUtils() {
    }

    private static final Logger LOG = LoggerFactory.getLogger(KeyGeneratorUtils.class);
    public static void main(String[] args) {
        // System.out.println(getRandomString(64));
        // System.out.println(getRandomString(64));
    }

    public static String generalKey(String jwtKey) {
        byte[] encodedKey = Base64.decodeBase64(jwtKey);//本地的密码解码[B@152f6e2
        return Base64.encodeBase64URLSafeString(encodedKey);
    }

    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    static SecretKey generateSecretKey() {
        SecretKey hmacKey;
        try {
            // SignatureAlgorithm.HS512  "HmacSha256"

            hmacKey = KeyGenerator.getInstance(JWSAlgorithm.HS256.getName()).generateKey();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return hmacKey;
    }

}
